package com.pkk.cloud.support.gataway.spring.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @description: 请求基本的过滤
 * @author: peikunkun
 * @create: 2019-08-02 18:58
 **/
//定义一个RequestGatewayFilterFactory类实现AbstractGatewayFilterFactory接口。
//类名一定要为filterName + GatewayFilterFactory，如这里定义为RequestGatewayFilterFactory的话，它的filterName就是Request
@Slf4j
@Component
public class RequestGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {


  /**
   * @Description: 过滤的配置
   * @Param: [config]
   * @return: org.springframework.cloud.gateway.filter.GatewayFilter
   * @Author: peikunkun
   * @Date: 2019/8/11 0011 下午 7:39
   */
  @Override
  public GatewayFilter apply(Object config) {
    log.error("经过了请求过滤器:" + this.getClass().getSimpleName());
    return (exchange, chain) -> {
      //return chain.filter(exchange);
      String jwtToken = exchange.getRequest().getHeaders().getFirst("Authorization");
      String filter = exchange.getRequest().getQueryParams().getFirst("filter");

      //校验jwtToken的合法性
      /*if (JwtUtil.verifyToken(jwtToken) != null) {
        //合法
        return chain.filter(exchange);
      }*/

      if (StringUtils.isBlank(filter) || "false".equals(filter)) {
        return chain.filter(exchange);
      }

      //不合法
      ServerHttpResponse response = exchange.getResponse();
      //设置headers
      HttpHeaders httpHeaders = response.getHeaders();
      httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
      httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");

      JSONObject responseJson = new JSONObject();
      responseJson.put("code", "500");
      responseJson.put("msg", "错误");
      //设置body
      DataBuffer bodyDataBuffer = response.bufferFactory().wrap(responseJson.toJSONString().getBytes());
      return response.writeWith(Mono.just(bodyDataBuffer));
    };
  }
}
